package com.baicaoyuan.web.controller;

import com.alibaba.fastjson.JSON;
import com.baicaoyuan.web.common.CheckPower;
import com.baicaoyuan.web.common.LogUtil;
import com.baicaoyuan.web.common.Status;
import com.baicaoyuan.web.common.StringUtils;
import com.baicaoyuan.web.common.annotation.MemberAccess;
import com.baicaoyuan.web.common.excel.ExcelUtils;
import com.baicaoyuan.web.common.excel.LotteryScoreInput;
import com.baicaoyuan.web.common.exception.StateMessage;
import com.baicaoyuan.web.model.LotteryScoreInputDetailDO;
import com.baicaoyuan.web.model.UserDO;
import com.baicaoyuan.web.request.BaseRequest;
import com.baicaoyuan.web.request.br.*;
import com.baicaoyuan.web.response.LotteryResultResponse;
import com.baicaoyuan.web.response.LotteryUserExtResponse;
import com.baicaoyuan.web.response.LotteryUserResponse;
import com.baicaoyuan.web.response.UserResponse;
import com.baicaoyuan.web.service.LotteryService;
import com.baicaoyuan.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(value = "抽奖Controller", tags = {"抽奖操作接口"})
@RestController
@RequestMapping(value = "/lottery")
public class LotteryController {


    @Autowired
    CheckPower checkPower;

    @Autowired
    private LotteryService lotteryService;

    @Autowired
    UserService userService;

    @ApiOperation(value = "后台-excel抽奖积分导入模版（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/lotteryInput/periodNos/profit/excel/import", method = RequestMethod.POST)
    @ResponseBody
    public Status importExcelOfJzzProfitInput(@RequestParam(value = "uploadFile") MultipartFile file,
                                              @RequestParam(value = "token") String token,
                                              @RequestParam(value = "userId") Long userId) {
        try {

            checkPower(token, userId);

            List<LotteryScoreInput> list = ExcelUtils.readExcel("", LotteryScoreInput.class, file);

            list.forEach(
                    b -> System.out.println(JSON.toJSONString(b))
            );

            boolean r = lotteryService.saveLotteryScoreInput(list, userId);

            Status result = new Status(r ? StateMessage.SUCCESS : StateMessage.FAILED);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    private void checkPower(String token, Long userId) throws Exception {
        if (userService.checkToken(userId, token)) {
            UserDO userDO = userService.findOne(userId);

            if ("1".equals(userDO.getStatus()) && "3".equals(userDO.getWebAdmin())) {

            } else {
                throw new Exception("无权限");
            }
        } else {
            throw new Exception("无权限");
        }
    }

    @ApiOperation(value = "抽奖-app端（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/generateAward", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status generateAward(@RequestBody BLotteryDomainsGenerateRequest request) {
        try {
            LotteryResultResponse response = lotteryService.generateAward(request);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", response);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }


    @ApiOperation(value = "奖项内容获取-app端（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status list(@RequestBody BLotteryDomainsListGetRequest request) {
        try {
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("items", lotteryService.listLotteryItems(request.getLotteryProjectId()));
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "后台-奖项列表获取（token）", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/listLotteryProjects", method = RequestMethod.POST)
    @MemberAccess
    @ResponseBody
    public Status listLotteryProjects(@RequestBody BaseRequest request) {
        try {
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("projects", lotteryService.listLotteryProject());
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "后台-奖项设置保存(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/saveLotteryProject", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status saveLotteryProject(@RequestBody BAddLotteryProjectRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());
            Boolean r = lotteryService.saveLotteryProject(request);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "后台-奖项设置更新(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/updateLotteryProject", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status updateLotteryProject(@RequestBody BAddLotteryProjectRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());
            Boolean r = lotteryService.updateLotteryProject(request);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("result", r);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED, ex.getMessage());
        }
    }

    @ApiOperation(value = "后台-获取中奖用户列表(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/getLotteryUser", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status getLotteryUser(@RequestBody BLotteryUserPageRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());
            List<LotteryUserExtResponse> lotteryUser = lotteryService.getLotteryUserPage(request);
            Integer count = lotteryService.getCountOfAll(request);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("lotteryUser", lotteryUser);
            result.setData("totalCount", count);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "后台-兑奖(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/lotteryOver", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status lotteryOver(@RequestBody BLotteryOverRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());
            if (request.getIds().size() == 0) {
                Status s = new Status(StateMessage.FAILED);
                s.setMessage("没有id");
                return s;
            }
            Status result = new Status(StateMessage.SUCCESS);
            result.setState(lotteryService.lotteryOver(request));
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }

    @ApiOperation(value = "后台-积分导入情况(token)", notes = "", code = 200, produces = "application/json")
    @RequestMapping(value = "/listLotteryScorePage", method = RequestMethod.POST)
    @ResponseBody
    @MemberAccess
    public Status listLotteryScorePage(@RequestBody BLotteryScorePageRequest request) {
        try {
            checkPower.checkPower(request.getToken(), request.getUserId());
            List<LotteryScoreInputDetailDO> lotteryUser = lotteryService.getLotteryScorePage(request);
            Integer count = lotteryService.getLotteryScoreCountOfAll(request);
            Status result = new Status(StateMessage.SUCCESS);
            result.setData("lotteryScore", lotteryUser);
            result.setData("totalCount", count);
            return result;
        } catch (Exception ex) {
            LogUtil.Error("", ex);
            return new Status(StateMessage.FAILED);
        }
    }
}
